﻿using System;
using System.Collections.Generic;
using System.Web.Mvc;
using Microsoft.Web.WebPages.OAuth;
using prjYan.Forum.Filters;
using prjYan.Forum.Models;
using YanForum.Engine.ViewModels;
using WebMatrix.WebData;
using System.Web.Security;
using prjYan.Forum.Controllers;

namespace prjYan.Forum.Areas.Admin.Controllers
{
    [Authorize]
    [InitializeSimpleMembership]
    public class AccountAdminController : BaseController
    {
        private static int PageSize = 20;
        //
        // GET: /Admin/Account/

        public ActionResult Index()
        {
            var model = YanForum.Engine.Services.Account.GetUserByUserId(GetUserId);

            return View(model);
        }

        [HttpPost]
        public ActionResult Index(YanForum.Engine.ViewModels.UserItem model)
        {
            if (ModelState.IsValid)
            {
                //CheckNull
                if (!string.IsNullOrEmpty(model.ImagePath) && model.ImagePath != "/")
                {
                    model.Folder = model.ImagePath.Substring(0, 6);
                    model.Avatar = "1x1_" + model.ImagePath.Substring(7);
                }
                else
                {
                    model.Avatar = "";
                    model.Folder = "";
                }
                YanForum.Engine.Services.Account.UpdateUserById(model);
                ViewBag.Success = "Đã cập nhật thành công.";
                return View(model);
            }
            return View(model);
        }

        #region Cập nhật mật khẩu

        public ActionResult Manage(ManageMessageId? message)
        {
            ViewBag.StatusMessage =
                message == ManageMessageId.ChangePasswordSuccess ? "Mật khẩu của bạn đã được thay đổi."
                : message == ManageMessageId.SetPasswordSuccess ? "Mật khẩu của bạn đã được thêm."
                : message == ManageMessageId.RemoveLoginSuccess ? "The external login was removed."
                : "";
            ViewBag.HasLocalPassword = OAuthWebSecurity.HasLocalAccount(WebSecurity.GetUserId(User.Identity.Name));
            ViewBag.ReturnUrl = Url.Action("Manage");
            return View();
        }

        //
        // POST: /Account/Manage

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Manage(LocalPasswordModel model)
        {
            bool hasLocalAccount = OAuthWebSecurity.HasLocalAccount(WebSecurity.GetUserId(User.Identity.Name));
            ViewBag.HasLocalPassword = hasLocalAccount;
            ViewBag.ReturnUrl = Url.Action("Manage");
            if (hasLocalAccount)
            {
                if (ModelState.IsValid)
                {
                    // ChangePassword will throw an exception rather than return false in certain failure scenarios.
                    bool changePasswordSucceeded;
                    try
                    {
                        changePasswordSucceeded = WebSecurity.ChangePassword(User.Identity.Name, model.OldPassword, model.NewPassword);
                    }
                    catch (Exception)
                    {
                        changePasswordSucceeded = false;
                    }

                    if (changePasswordSucceeded)
                    {
                        return RedirectToAction("Manage", new { Message = ManageMessageId.ChangePasswordSuccess });
                    }
                    else
                    {
                        ModelState.AddModelError("", "Mật khẩu cũ không đúng, vui lòng kiểm tra lại.");
                    }
                }
            }
            else
            {
                // User does not have a local password so remove any validation errors caused by a missing
                // OldPassword field
                ModelState state = ModelState["OldPassword"];
                if (state != null)
                {
                    state.Errors.Clear();
                }

                if (ModelState.IsValid)
                {
                    try
                    {
                        WebSecurity.CreateAccount(User.Identity.Name, model.NewPassword);
                        return RedirectToAction("Manage", new { Message = ManageMessageId.SetPasswordSuccess });
                    }
                    catch (Exception e)
                    {
                        ModelState.AddModelError("", e);
                    }
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        [ChildActionOnly]
        public ActionResult RemoveExternalLogins()
        {
            ICollection<OAuthAccount> accounts = OAuthWebSecurity.GetAccountsFromUserName(User.Identity.Name);
            List<ExternalLogin> externalLogins = new List<ExternalLogin>();
            foreach (OAuthAccount account in accounts)
            {
                AuthenticationClientData clientData = OAuthWebSecurity.GetOAuthClientData(account.Provider);

                externalLogins.Add(new ExternalLogin
                {
                    Provider = account.Provider,
                    ProviderDisplayName = clientData.DisplayName,
                    ProviderUserId = account.ProviderUserId,
                });
            }

            ViewBag.ShowRemoveButton = externalLogins.Count > 1 || OAuthWebSecurity.HasLocalAccount(WebSecurity.GetUserId(User.Identity.Name));
            return PartialView("_RemoveExternalLoginsPartial", externalLogins);
        }


        #endregion

        #region Quản lý tài khoản

        [Authorize(Roles = YanForum.Engine.ViewModels.UserRoles.Admin)]
        public ActionResult ManageAccount(YanForum.Engine.ViewModels.UserOptions options, int p = 1)
        {
            options.ListRole = YanForum.Engine.Services.Account.GetListRole();
            var model = YanForum.Engine.Services.Account.GetListUser(PageSize, p, options);
            return View(model);
        }

        [Authorize(Roles = YanForum.Engine.ViewModels.UserRoles.Admin)]
        public ActionResult AjaxDeleteUser(int userId)
        {
            try
            {
                //Xóa: set role = Banned
                if (userId != 0 && userId != GetUserId)
                {
                    YanForum.Engine.Services.Account.UpdateUserRole(userId, (int)YanForum.Engine.ViewModels.RoleEnum.Banned);
                }
                return Json(new { status = true });
            }
            catch (Exception ex)
            {
                return Json(new { status = false, message = ex.Message });
            }
        }

        [Authorize(Roles = YanForum.Engine.ViewModels.UserRoles.Admin)]
        public ActionResult SetPassWord(int id)
        {
            if (id == GetUserId)
                return RedirectToAction("ManageAccount");

            var getUser = YanForum.Engine.Services.Account.GetUserByUserId(id);
            var model = new YanForum.Engine.ViewModels.PasswordModel();
            model.UserId = id;
            model.UserName = getUser.UserName;
            model.RoleId = getUser.RoleId;

            return View(model);
        }

        [HttpPost]
        [Authorize(Roles = YanForum.Engine.ViewModels.UserRoles.Admin)]
        [ValidateAntiForgeryToken]
        public ActionResult SetPassWord(YanForum.Engine.ViewModels.PasswordModel model)
        {
            if (string.IsNullOrEmpty(model.NewPassword))
            {
                //Update Role
                YanForum.Engine.Services.Account.UpdateUserRole(model.UserId, model.RoleId);
                ViewBag.Success = "Đã cập nhật role";
            }
            else
            {
                if (ModelState.IsValid)
                {
                    //User can cap nhat khong duoc trung voi user hien tai
                    if (model.UserId == GetUserId)
                        return RedirectToAction("ManageAccount");

                    //Update Role
                    YanForum.Engine.Services.Account.UpdateUserRole(model.UserId, model.RoleId);

                    bool hasLocalAccount = OAuthWebSecurity.HasLocalAccount(WebSecurity.GetUserId(model.UserName));

                    if (hasLocalAccount)
                    {
                        var token = WebSecurity.GeneratePasswordResetToken(model.UserName);
                        WebSecurity.ResetPassword(token, model.NewPassword);
                        ViewBag.Success = "Đã cập nhật mật khẩu";

                        return View(model);
                    }
                    else
                    {
                        try
                        {
                            WebSecurity.CreateAccount(model.UserName, model.NewPassword);
                            ViewBag.Success = "Đã cập nhật mật khẩu mới";
                            return View(model);
                        }
                        catch (Exception e)
                        {
                            ModelState.AddModelError("", e);
                        }
                        return View(model);
                    }
                }
            }

            return View(model);
        }

        #endregion
    }
}
